package com.jxd.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import com.jxd.mapper.EventRecordMapper;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;

import com.jxd.config.HbaseConfig;
import com.jxd.entity.MesHead;
import com.jxd.hbase.utils.HBaseUtils;
import com.jxd.hbase.utils.QurryTableUntil;
import com.jxd.model.EventRecord;
import com.jxd.repositories.MesHeadRepositories;
import com.jxd.service.EventRecordService;
import com.jxd.service.ProcessStaticService;
import com.jxd.service.ShipInformationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ProcessStaticServiceImpl implements ProcessStaticService {

    @Value("${hbase.bwcontent.tablename}")
    private String bwContentTableName;

    @Autowired
    HbaseConfig hbaseConfig;

    @Autowired
    @Qualifier("mesHeadRepositories")
    MesHeadRepositories mesHeadRepositories;

    @Autowired
    @Qualifier("getHtableByMesHead")
    HTable mesHeadClient;

    @Autowired
    @Qualifier("getHtableByMesContent")
    HTable mesContentClient;

    @Autowired
    ShipInformationService shipInformationService;

    @Resource
	EventRecordMapper eventRecordMapper;
    
    @Resource
    EventRecordService eventRecordService;


    public List<MesHead> getLaunchMesHead(String fileName, String mesId, String shipId) {
        //创建B0BF返回数组
        List<MesHead> mesHeads = new ArrayList<>();
        //获取所有单步控制报文41040
        List<MesHead> mesHeadList = mesHeadRepositories.findAllByFileNameAndMesIdAndShipId(fileName, mesId, shipId);
        //获取第六行为B0BF的报文
//		for(int i=0;i<mesHeads.size();i++) {
//			String mesSignId = mesHeads.get(i).getMesSignId();
//			String rowKey = mesSignId+"-6";
//			Get get = new Get(Bytes.toBytes(rowKey));
//			try {
//				Result rs = mesContentClient.get(get);
//				String val = Bytes.toString(rs.getValue(Bytes.toBytes("f1"), Bytes.toBytes("code")))
//                        .replace("'", "");
//				if(!"B0BF".equals(val)) {
//					mesHeads.remove(i);
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} finally {
//                IOUtils.closeStream(mesContentClient);
//            }
//		}
        List<String> rowkeys = new ArrayList<String>();
        for (int i = 0; i < mesHeadList.size(); i++) {
            String mesSignId = mesHeadList.get(i).getMesSignId();
            String rowKey = mesSignId + "-6";
            rowkeys.add(rowKey);
        }
        QurryTableUntil qurryTableUntil = new QurryTableUntil();
        Connection connection = hbaseConfig.HbaseConnection();
        List<String> codes = qurryTableUntil.qurryBwContentVal(rowkeys, bwContentTableName, connection);
        for (int i = 0; i < codes.size(); i++) {
            if ("B0BF".equals(codes.get(i))) {
                mesHeads.add(mesHeadList.get(i));
            }
        }
        return mesHeads;
    }

    public List<EventRecord> getLaunchRecord(List<MesHead> mesHeads) {
    	
    	SimpleDateFormat nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<EventRecord> eventRecords = new ArrayList<EventRecord>();
        List<String> eventtyperowkeys = new ArrayList<String>();
        QurryTableUntil qurryTableUntil = new QurryTableUntil();
        Connection connection = hbaseConfig.HbaseConnection();
        List<String> rowkey5s = new ArrayList<String>();
        List<String> rowkey4s = new ArrayList<String>();
        List<String> rowkey3s = new ArrayList<String>();
        List<String> rowkey2s = new ArrayList<String>();
        List<String> typeMesSignIds = new ArrayList<String>();
        
        for (int i = 0; i < mesHeads.size(); i++) {
            EventRecord eventRecord = new EventRecord();
            //获取文件名称
            String fileName = mesHeads.get(i).getFileName();
            eventRecord.setFilename(fileName);
            //获取流程关键时间
            eventRecord.setGjsj(mesHeads.get(i).getMesDate().substring(0, 11) + mesHeads.get(i).getMesTime());
            //获取mesSignId
            String mesSignid = mesHeads.get(i).getMesSignId();
            //获取接收设备
            String receiveDevice = mesHeads.get(i).getReceivingDevice();
            //获取发送设备
            String sendDevice = mesHeads.get(i).getSendDevice();
            //获取舷号
            String shipName = mesHeads.get(i).getShipId();
            String shipId = shipInformationService.selectbyXtbh(shipName);
            eventRecord.setUnitid(shipId);

            //获取向上首条61616报文
            List<MesHead> typeMesHeadsBefore = mesHeadRepositories
                    .findAllByFileNameAndMesIdAndMesSignIdBefore(
                            fileName,
                            "61616",
                            mesSignid,
                            Sort.by(Sort.Order.desc("mesDate")));
            String typeMesSignId = typeMesHeadsBefore.get(0).getMesSignId(); //10000-22
            String rowkey_5 = mesSignid + "-5";
            String rowkey_4 = mesSignid + "-4";
            String rowkey_3 = mesSignid + "-3";
            String rowkey_2 = mesSignid + "-2";
//            List<String> rowkeys = new ArrayList<String>();
            rowkey5s.add(rowkey_5);
            rowkey4s.add(rowkey_4);
            rowkey3s.add(rowkey_3);
            rowkey2s.add(rowkey_2);
            typeMesSignIds.add(typeMesSignId);
            //单类型？
//            List<String> codes = qurryTableUntil.qurryBwContentVal(rowkeys, bwContentTableName, connection);
            //获取库号
//            String val5 = codes.get(0).substring(3, 4);
            //获取单元号
//            String val4 = codes.get(1).substring(1, 2);
            //获取模块号
//            String val3 = codes.get(2).substring(3, 4);
            //获取单类型
//            String val2 = codes.get(3).substring(3, 4);
            //拼接单元序号
//            String unitNumber = val5 + val4 + val3 + val2;
//            eventRecord.setUnitname(unitNumber);
//            System.out.println("第"+i+"次获取61616报文单类型开始:"+ nowtime.format(new Date()));
            //获取61616报文单类型
//            String eventtypeRowkey = typeMesSignId + "-" + String.valueOf(Integer.parseInt(val3) * 18 + 1);
//            eventtyperowkeys.add(eventtypeRowkey);
//            Get get = new Get(Bytes.toBytes(eventtypeRowkey));
//            try {
//                Result rs = mesContentClient.get(get);
//                String eventtype = Bytes.toString(rs.getValue(Bytes.toBytes("f1"), Bytes.toBytes("code")));
//				if (eventtype != null) {
//					eventtype=eventtype .replace("'", "");
//				}
//                eventRecord.setEventtype(eventtype);
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } finally {
//                IOUtils.closeStream(mesContentClient);
//            }


            //获取向下首条41008报文
            List<MesHead> mesHeadsAfter
                    = mesHeadRepositories
                    .findAllByFileNameAndMesIdAndShipIdAndReceivingDeviceAndSendDeviceAndMesSignIdAfter(
                            fileName,
                            "41008",
                            shipId,
                            receiveDevice,
                            sendDevice,
                            mesSignid,
                            Sort.by(Sort.Order.asc("mesDate")));
            //没有怎置空
            //获取结束时间
            String endTime = "";
            if (mesHeadsAfter.size() != 0) {
                MesHead endTimeMesHead = mesHeadsAfter.get(0);
                endTime = endTimeMesHead.getMesDate().substring(0, 11) + endTimeMesHead.getMesTime();
                eventRecord.setEndtime(endTime);
            } else {
                eventRecord.setEndtime(endTime);
            }
            //获取向上首条41008报文
            List<MesHead> mesHeadsBefore
                    = mesHeadRepositories
                    .findAllByFileNameAndMesIdAndShipIdAndReceivingDeviceAndSendDeviceAndMesSignIdBefore(
                            fileName,
                            "41008",
                            shipId,
                            receiveDevice,
                            sendDevice,
                            mesSignid,
                            Sort.by(Sort.Order.desc("mesDate")));
			//没有怎置空
            //获取结束时间
            String startTime = "";
            if (mesHeadsAfter.size() != 0) {
                MesHead startTimeMesHead = mesHeadsBefore.get(0);
                startTime = startTimeMesHead.getMesDate().substring(0, 11) + startTimeMesHead.getMesTime();
                eventRecord.setEndtime(startTime);
            } else {
                eventRecord.setEndtime(startTime);
            }
            eventRecord.setId(UUID.randomUUID().toString().replace("-", ""));
            eventRecords.add(eventRecord);
        }
        System.out.println("开始从Hbase取数："+nowtime.format(new Date()));
        //获取单元号
        List<String> val5s = qurryTableUntil.qurryBwContentVal(rowkey5s, bwContentTableName, connection);
        List<String> val4s = qurryTableUntil.qurryBwContentVal(rowkey4s, bwContentTableName, connection);
        List<String> val3s = qurryTableUntil.qurryBwContentVal(rowkey3s, bwContentTableName, connection);
        List<String> val2s = qurryTableUntil.qurryBwContentVal(rowkey2s, bwContentTableName, connection);
        for(int i = 0;i<eventRecords.size();i++) {
        	String unitNumber = val5s.get(i) + val4s.get(i) + val3s.get(i) + val2s.get(i);
        	eventRecords.get(i).setUnitname(unitNumber);
        	String eventtype = typeMesSignIds.get(i) + '-' + String.valueOf(Integer.parseInt(val3s.get(i)) * 18 + 1);
        	eventtyperowkeys.add(eventtype);
        }
        //获取所有61616报文单类型
        List<String> eventtypes = qurryTableUntil.qurryBwContentVal(eventtyperowkeys, bwContentTableName, connection);
        System.out.println("eventtypes.size()="+eventtypes.size());
        System.out.println("eventRecords.size()="+eventRecords.size());
        //给每一个记录的单类型赋值
        for(int i=0;i<eventRecords.size();i++) {
        	eventRecords.get(i).setEventtype(eventtypes.get(i));
        }
        System.out.println("开始给各条记录的eventid赋值："+nowtime.format(new Date()));
        //给各条记录的eventid赋值
        for (int t = 0; t < eventRecords.size(); t++) {
            if (eventRecords.get(t).getEventid() == null) {
                String value1 = eventRecords.get(t).getEndtime();
                String value2 = eventRecords.get(t).getStarttime();
                String uuid = UUID.randomUUID().toString().replace("-", "");
                eventRecords.get(t).setEventid(uuid);
                for (int p = t; p < eventRecords.size(); p++) {
                    if (value1.equals(eventRecords.get(p).getEndtime()) && value2.equals(eventRecords.get(p).getStarttime())) {
                        eventRecords.get(p).setEventid(uuid);
                    }
                }
            }
        }

        return eventRecords;
    }

    public List<EventRecord> getEventRecords(String filename, String shipid) throws IOException, ParseException{
    	String baseRowKey = "1,"+filename+","+shipid+",";
    	List<EventRecord> eventRecords = new ArrayList<EventRecord>();
    	//获取所有单步控制报文41040
    	Iterator<Result> iterator = HBaseUtils.getLineByStartKeyAndEndKey(baseRowKey + "41040", baseRowKey + "41041");
    	while(iterator.hasNext()) {
    		Result rs = iterator.next();
    		String code = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes("6"))).replace("'", "");
    		//获取第六行为B0BF的报文
    		if("B0BF".equals(code)) {
    			EventRecord eventRecord = new EventRecord();
    			//获取文件名称
    			eventRecord.setFilename(filename);
    			//获取流程关键时间
    			String mesdate = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.MES_DATE))).replace("'", "");
    			String mestime = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.MES_TIME))).replace("'", "");
                eventRecord.setGjsj(mesdate.substring(0,11)+mestime.replace(".", ":"));
                //获取舷号
                String shipId = shipInformationService.selectbyXtbh(shipid);
                eventRecord.setUnitid(shipId);
                //获取接收设备
                String receiveDevice = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.RECEIVE_DEVICE))).replace("'", "");
                //获取发送设备
                String sendDevice = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.SEND_DEVICE))).replace("'", "");
                //获取单元号
                String val5 = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes("5"))).replace("'", "").substring(3,4);
                String val4 = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes("4"))).replace("'", "").substring(1,2);
                String val3 = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes("3"))).replace("'", "").substring(3,4);
                String val2 = Bytes.toString(rs.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes("2"))).replace("'", "").substring(3,4);
                String unitname = val5 + val4 + val3 + val2;
                eventRecord.setUnitname(unitname);
                //获取向上首条61616报文
                String startKey = baseRowKey + "61616," + HBaseUtils.getChangedStrDate(mesdate, -20);
                String endKey = baseRowKey + "61616," + mesdate;
                Iterator<Result> resultIterator = HBaseUtils.getLineByStartKeyAndEndKey(startKey, endKey);
                String missileType = "";
                Result rs1;
                while (resultIterator.hasNext()) {
                    rs1 = resultIterator.next();
                    missileType = Bytes.toString(rs1.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(String.valueOf(Integer.parseInt(val3) * 18 + 1)))).replace("'", "");
                }
                eventRecord.setEventtype(missileType);
                //获取向上首条41008报文
                String startKeyStartTime = baseRowKey + "41008," + HBaseUtils.getChangedStrDate(mesdate, -20);
                String endKeyStartTime = baseRowKey + "41008," + mesdate;
                Iterator<Result> startTimeIterator = HBaseUtils.getLineByStartKeyAndEndKey(startKeyStartTime, endKeyStartTime);
                //获取开始时间
                String startTime = "";
                while (startTimeIterator.hasNext()) {
                    Result startRS = startTimeIterator.next();
                    String recieveDeviceSttime = Bytes.toString(startRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.RECEIVE_DEVICE))).replace("'", "");
                    String sendDeviceSttime = Bytes.toString(startRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.SEND_DEVICE))).replace("'", "");
                    if(recieveDeviceSttime.equals(receiveDevice) && sendDeviceSttime.equals(sendDevice)) {
                    	startTime = Bytes.toString(startRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.MES_DATE))).replace("'", "").substring(0, 11)
                            + Bytes.toString(startRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.MES_TIME))).replace("'", "").replace(".", ":");
                    }
                }
                eventRecord.setEndtime(startTime);
                //获取向下首条41008报文
                String startKeyEndTime = baseRowKey + "41008," + mesdate;
                String endKeyEndTime = baseRowKey + "41008," + HBaseUtils.getChangedStrDate(mesdate, 20);
                Iterator<Result> endTimeIterator = HBaseUtils.getLineByStartKeyAndEndKey(startKeyEndTime, endKeyEndTime);
                //获取结束时间
                String endTime = "";
                while (endTimeIterator.hasNext()) {
                    Result endRS = endTimeIterator.next();
                    String recieveDeviceEndtime = Bytes.toString(endRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.RECEIVE_DEVICE))).replace("'", "");
                    String sendDeviceEndtime = Bytes.toString(endRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.SEND_DEVICE))).replace("'", "");
                    if(recieveDeviceEndtime.equals(receiveDevice) && sendDeviceEndtime.equals(sendDevice)) {
                    	endTime = Bytes.toString(endRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.MES_DATE))).replace("'", "").substring(0, 11)
                            + Bytes.toString(endRS.getValue(Bytes.toBytes(HBaseUtils.FAMILY), Bytes.toBytes(HBaseUtils.MES_TIME))).replace("'", "").replace(".", ":");
                    	break;
                    }
                }
                eventRecord.setEndtime(endTime);
                eventRecord.setId(UUID.randomUUID().toString().replace("-", ""));
                eventRecords.add(eventRecord);
    		}
    	}
    	//给各条记录的eventid赋值
        for (int t = 0; t < eventRecords.size(); t++) {
            if (eventRecords.get(t).getEventid() == null) {
                String value1 = eventRecords.get(t).getEndtime();
                String value2 = eventRecords.get(t).getStarttime();
                String uuid = UUID.randomUUID().toString().replace("-", "");
                eventRecords.get(t).setEventid(uuid);
                for (int p = t; p < eventRecords.size(); p++) {
                    if (value1.equals(eventRecords.get(p).getEndtime()) && value2.equals(eventRecords.get(p).getStarttime())) {
                        eventRecords.get(p).setEventid(uuid);
                    }
                }
            }
        }
    	return eventRecords;
    }
    
    public void insertEventRecord(List<EventRecord> eventRecords) {
            eventRecordService.insertList(eventRecords);
    }
}
